package link.hwx.controller.u9;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import link.hwx.service.oa.OaInfoService;
import link.hwx.util.AjaxResult;
import link.hwx.util.CommonSetData;
import link.hwx.util.HttpManager;
import link.hwx.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用款申请
 */

@RestController
@RequestMapping("/cx/srm")
public class SrmPayApplyOpenApi {
    @Autowired
    private OaInfoService oaInfoMapper;

    @PostMapping("/createPayApply")
    public AjaxResult sCreatePo(@RequestBody Map<String, Object> jsonStr) {
        if (jsonStr == null) {
            Map<String, Object> result = new HashMap<String, Object>();
            return AjaxResult.error("数据不能为空!");
        }
//        0 --无预付 发票
//        1 -- 预付
//        2 -- 非srm业务
        Object fkly = jsonStr.get("fkly");
        int i = safeToInt(fkly, -1);
        if (2 == i || i == -1) {
            return AjaxResult.success();
        }

        String result = createPr(jsonStr);
        if (StringUtils.isNotEmpty(result)) {
            JSONObject resultmap = JSON.parseObject(result);
            if (resultmap.getBoolean("Success")) {
//                String mCode = resultmap.getString("VoucherCode");
//                String requestId = jsonStr.get("requestId") + "";
                //修改oa表单标题
                //oaInfoService.updateWorkflowTableTitle(" srm" + mCode, "73098", "6");
                //回写srm单号
                //oaInfoMapper.updateSdByRequestId(CommonSetData.oaShippingDemandTableMainDbNameD, " srm" + mCode, requestId);
                return AjaxResult.success();
            } else {
                return AjaxResult.error(resultmap.getString("Message"));
            }
        }
        return AjaxResult.error();
    }

    public String createPr(Map<String, Object> oaMapData) {
        String srmUrl = CommonSetData.serveSrmIp + CommonSetData.srmPayApplyUrlCreat;
        String userpwd = StringUtil.md5(CommonSetData.srmUserPwd);
        JSONObject user = new JSONObject();
        user.put("usercode", CommonSetData.srmUserCode);
        user.put("userpwd", userpwd);
        JSONObject voucher = new JSONObject();
        voucher.put("voucherno", CommonSetData.payApplyVoucherno);
        voucher.put("formid", CommonSetData.payApplyFormid);
        //组装head头数据
        JSONObject head = new JSONObject();
        head.put("ccode", oaMapData.get("requestId"));
        String result = null;
        String fkly = oaMapData.get("fkly").toString();
        if ("0".equals(fkly)) {
            result = "应付款";
        } else {
            result = "预付款";
        }
        head.put("cbitprepayment", result);//款项类型
        head.put("cmakercode", oaMapData.get("zdr1"));//制单人id
        head.put("cflag", oaMapData.get("cflag"));//新增、归档、退回
        //组装body数据
        JSONObject armbody = new JSONObject();
        JSONArray focus_srm_paymentfilingc = new JSONArray();
        List<List<Map<String, Object>>> detailList = (List<List<Map<String, Object>>>) oaMapData.get("detailData");
        for (int i = 0; i < detailList.size(); i++) {
            for (int j = 0; j < detailList.get(i).size(); j++) {
                Map<String, Object> detal = detailList.get(i).get(j);//列数据;
                JSONObject srmLine = new JSONObject();
                srmLine.put("clineid", detal.get("keyid"));
                srmLine.put("imoney", detal.get("bcfkje"));


                //处理附件
//                if (detal.get("scfj")!=null&&detal.get("scfj")!=""){
//                    String sjarry[] = detal.get("scfj").toString().split(",");
//                    OaUserInfo filemap = oaInfoMapper.findFileInfoByDocID(String.valueOf(sjarry[0]));
//                    String filename = filemap.getImagefilename();
//                    String filepath = filemap.getFilerealpath();
//                    if (StringUtils.isNotBlank(filepath)) {
//                        String zipFilePath = filepath;
//                        String destDirectory = CommonSetData.oaZCFilePath;
//                        String fileName = UnzipUtil.unzip(zipFilePath, destDirectory);
//                        String base64str = "";
//                        try {
//                            String filetype = ".pdf";
//                       /* if (StringUtils.isNotBlank(filename)) {
//                            filetype = filename.substring(filename.lastIndexOf("."));
//                        }*/
//                            // String strname = zipFilePath.substring(zipFilePath.lastIndexOf("\\") + 1, zipFilePath.lastIndexOf("."));
//                            String newFileUrl = destDirectory + File.separator + fileName;
//                            File file = new File(newFileUrl);
//                            base64str = Base64Util.fileToBase64Str(file);
//                            System.out.println(base64str);
//                            file.delete();//删除文件
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                        Map<String, String> fileInfo = new HashMap<String, String>();
//                        fileInfo.put("filename", filename);
//                        fileInfo.put("buffer", base64str);
//
//                        srmLine.put("caccessory", fileInfo);
//                    } else {
//                        srmLine.put("caccessory", "");
//                    }}
                focus_srm_paymentfilingc.add(srmLine);
            }
        }
        armbody.put("focus_srm_paymentfilingc", focus_srm_paymentfilingc);
        JSONObject datatable = new JSONObject();
        datatable.put("user", user);
        datatable.put("voucher", voucher);
        datatable.put("head", head);
        datatable.put("body", armbody);
        String data = JSON.toJSONString(datatable);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
        builder.addTextBody("data", data, contentType);
        String s1 = HttpManager.sendPostFormData(srmUrl, builder,data);
        // System.out.println("qingoudan11111:"+builder);
        //String s1 = doPostformdata(srmUrl, data);
        return s1;

    }

    public int safeToInt(Object obj, int defaultValue) {
        if (obj == null) {
            return defaultValue; // 默认值
        }
        if (obj instanceof Integer) {
            return (Integer) obj; // 已经是 Integer
        }
        if (obj instanceof Number) { // 包括 Long、Double、Float 等
            return ((Number) obj).intValue(); // 转换为 int
        }
        try {
            return Integer.parseInt(obj.toString()); // 尝试解析字符串
        } catch (NumberFormatException e) {
            return defaultValue; // 解析失败返回默认值
        }
    }
}
